/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
  useNamespace,
  useControlController,
  hasEmptyPanelRenderer,
  IBizCustomRender,
} from '@ibiz-template/vue3-util';
import { defineComponent, PropType, Ref, ref, VNode } from 'vue';
import { IDEGrid } from '@ibiz/model-core';
import { IControlProvider } from '@ibiz-template/runtime';
import { PivotTableController } from './pivottable.controller';
import { VPivottableUiShell } from './pivottable/components';
import './pivottable.scss';

export const PivotTable = defineComponent({
  name: 'IBizPivotTable',
  components: {
    vuePivotTableUiShell: VPivottableUiShell,
  },
  props: {
    /**
     * @description 表格模型数据
     */
    modelData: { type: Object as PropType<IDEGrid>, required: true },
    /**
     * @description 应用上下文对象
     */
    context: { type: Object as PropType<IContext>, required: true },
    /**
     * @description 视图参数对象
     * @default {}
     */
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    /**
     * @description 部件适配器
     */
    provider: { type: Object as PropType<IControlProvider> },
    /**
     * @description 部件行数据默认激活模式，值为0:不激活，值为1：单击激活，值为2：双击激活
     */
    mdctrlActiveMode: { type: Number, default: undefined },
    /**
     * @description 是否单选
     */
    singleSelect: { type: Boolean, default: undefined },
    /**
     * @description 是否启用行编辑
     */
    rowEditOpen: { type: Boolean, default: undefined },
    /**
     * @description 是否是简单模式，即直接传入数据，不加载数据
     */
    isSimple: { type: Boolean, required: false },
    /**
     * @description 简单模式下传入的数据
     */
    data: { type: Array<IData>, required: false },
    /**
     * @description 是否默认加载数据
     * @default true
     */
    loadDefault: { type: Boolean, default: true },
  },
  setup() {
    const c = useControlController<PivotTableController>(
      (...args) => new PivotTableController(...args),
    );
    const ns = useNamespace(`pivot-table`);

    const items: Ref<IData[]> = ref([]);

    c.evt.on('onLoadSuccess', () => {
      const columns = Object.keys(c.columns);
      items.value = c.state.items.map(x => {
        const result: IData = {};
        columns.forEach(key => {
          result[key] = x[key];
        });
        return result;
      });
    });

    const renderNoData = (): VNode | null => {
      // 未加载不显示无数据
      const { isLoaded } = c.state;
      if (isLoaded) {
        const quickToolbar = c.model.controls?.find(
          item => item.name === `${c.model.name}_quicktoolbar`,
        );
        if (quickToolbar) {
          return (
            <iBizToolbarControl
              modelData={quickToolbar}
              context={c.context}
              params={c.params}
              class={ns.b('quick-toolbar')}
            ></iBizToolbarControl>
          );
        }
        const noDataSlots: IParams = {};
        if (hasEmptyPanelRenderer(c)) {
          Object.assign(noDataSlots, {
            customRender: () => (
              <IBizCustomRender controller={c}></IBizCustomRender>
            ),
          });
        }
        return (
          <iBizNoData
            text={c.model.emptyText}
            emptyTextLanguageRes={c.model.emptyTextLanguageRes}
            hideNoDataImage={c.state.hideNoDataImage}
          >
            {noDataSlots}
          </iBizNoData>
        );
      }
      // 给null 表格会绘制默认的无数据
      return <div></div>;
    };

    return {
      c,
      ns,
      items,
      renderNoData,
    };
  },
  render() {
    if (!this.items || !this.items.length) {
      return this.renderNoData();
    }
    const { cols = [], rows = [], vals = [] } = this.c.state.config;
    return (
      <vuePivotTableUiShell
        class={this.ns.b()}
        data={this.items}
        cols={cols}
        rows={rows}
        vals={vals}
        fields={this.c.state.fields}
        groupMode={this.c.groupMode}
        onChange={(data: IData) => {
          this.c.saveConfig(data);
        }}
      />
    );
  },
});
